package com.junson.client.codec;

import java.nio.charset.Charset;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class Decoder extends ByteToMessageDecoder {
	private Logger logger = LoggerFactory.getLogger(Decoder.class);
	private Charset charset;
	
	public Decoder() {
	}
	public Decoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		int headLength = Integer.BYTES;
		if (in.readableBytes() < headLength) {
			return;
		}

		in.markReaderIndex();
		int dataLength = in.readInt();  
		if (dataLength <= 0) {
			ctx.close();
			return;
		}
		if (in.readableBytes() < dataLength) {
			in.resetReaderIndex();
			return;
		}
		
		byte[] b = new byte[in.readableBytes()];
		logger.debug("Decoder===>" + new String(b, charset));
		in.readBytes(b);
		out.add(new String(b, charset));
	}

}
